var querystring = require('querystring');
var Step = require('./../common/step');
var users = require('./../common/UserCache');
var authorize = require('./../handler/authorize');

var actions = module.exports = {
    handlerNameField: 'handlerName',
    setup: function (cfg, app) {
        var me = this;
        if (!cfg || !app) {
            console.log("配置信息错误，不能正确配置Ext通讯协议。");
            return;
        }

        var bodyParser = require('body-parser');

        //用于解析 application/json
        app.use(bodyParser.json());

        //用于解析 application/x-www-form-urlencoded
        app.use(bodyParser.urlencoded({ extended: true }));

        var routerUrl = cfg.routerUrl;
        var handlerMapping;

        this.handlerMapping = handlerMapping = {};
        if (cfg.handlers && cfg.handlers instanceof Array && cfg.handlers.length > 0) {

            var handlers = cfg.handlers;

            for (var index = 0; index < handlers.length; index++) {

                var handler = handlers[index]
                    , handlerName;

                //排除没有handlerName的类
                if (!handler.hasOwnProperty(me.handlerNameField)) {
                    continue;
                }
                handlerName = handler[me.handlerNameField];
                handlerMapping[handlerName] = handler;
            }
        }

        //用于处理客户端的请求
        app.post(routerUrl, function (req, res) {
            var body = req.body,
                request;

            if (!body) {
                res.send("空的请求！");
                return;
            }

            var action = req.query.action
                , method = req.query.method;

            if (!action) {
                res.send(500, { error: '找不到action:' + action + '' });
                return;
            }

            var handler = handlerMapping[action];
            if (!handler) {
                res.send(500, { error: '找不到handler:' + handler + '' });
                return;
            }
            func = handler[method];

            if (!func) {
                res.send(500, { error: 'api不存在' });
                return;
            }

            try {
                body.req = req;
                body.res = res;
                authorize.validate(body, function (obj) {
                    if (obj.success) {
                        var callBackData = func(body);
                    } else {
                        res.send(500, { error: obj.detail });
                    }
                });
            } catch (error) {
                res.send(500, { error: JSON.stringify(error) });
            }
        });
    }
};